package com.party.jackclientandroid.controller;

import android.text.TextUtils;
import android.util.Log;

import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.MApplication;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.OSSConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.xiaosai.imagecompress.utils.BitmapUtil;

/**
 * Created by 派对 on 2018/10/28.
 */

public class AliOssService {

    private BaseActivity mContext;
    private MApplication mApplication;
    private AliyunOSSController ossController;
    private List<UploadImage> images;
    private UploadListener mSuccessListener;
    private UploadListener mFailListener;

    /**
     * 压缩之后的图片路径
     */
    private File targetDir;
    private int maxSize = 1024;


    public interface UploadListener {
        void handler(String message);
    }

    public AliOssService(BaseActivity context) {
        this.mContext = context;
        images = new ArrayList<>();
        mApplication = context.getmApplication();
        ossController = new AliyunOSSController(context);
    }

    public void uploadImageAll(UploadListener success) {
        uploadImageAll(success, (String message) -> {
            mContext.showToast("上传图片失败");
            mContext.hideAlertDialog();
        });
    }

    public void uploadImageAll(UploadListener success, UploadListener fail) {
        mSuccessListener = success;
        mFailListener = fail;
        mContext.addDisposableIoMain(ossController.getOssConfig(AliyunOSSController.OSS_BANNER), new DefaultConsumer<OSSConfig>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<OSSConfig> baseBean) {
                ossController.initOssConfig(baseBean.getData(), mContext);
                doUploadPictures(0);
            }
        });
    }

    /**
     * 使用同步压缩方式
     *
     * @param filePaths
     */
    private Observable<List<String>> compressPictures(List<String> filePaths) {
        return Observable
                .just(filePaths)
                .subscribeOn(Schedulers.io())
                .concatMap(new Function<List<String>, ObservableSource<List<String>>>() {
                    @Override
                    public ObservableSource<List<String>> apply(@NonNull List<String> list) throws Exception {
                        return Observable.just(compressPicturesSync(list));
                    }
                });
    }

    /**
     * 使用同步压缩方式
     *
     * @param filePaths
     */
    private List<String> compressPicturesSync(List<String> filePaths) {
        List<String> list = new ArrayList<>();
        for (String filePath : filePaths) {
            // 图片地址为null或者"",不进行压缩和添加
            if (TextUtils.isEmpty(filePath)) continue;
            // 如果路径是网络数据则不压缩
            if (filePath.contains("http://")) {
                list.add(filePath);
                continue;
            }
            String picture = compressPictureSync(filePath);
            if (picture != null) {
                list.add(picture);
            }
        }
        return list;
    }

    /**
     * 使用同步压缩方式
     *
     * @param filePath
     * @return
     */
    public String compressPictureSync(String filePath) {
        try {
            String targetCompressPath = getImageCacheFile(checkSuffix(filePath));
            String resultStr = BitmapUtil.compressBitmap(filePath, targetCompressPath, maxSize);
            if ("1".equals(resultStr)) {
                return targetCompressPath;
            } else {
                Log.e("compress", "onError==resultStr:" + resultStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("compress", "onError==msg:" + e.getMessage());
        }
        return null;
    }

    private String checkSuffix(String path) {
        if (TextUtils.isEmpty(path) || !path.contains(".")) {
            return ".jpg";
        }
        return path.substring(path.lastIndexOf("."), path.length());
    }


    private String getImageCacheFile(String suffix) {
        return targetDir + "/" +
                System.currentTimeMillis() +
                (int) (Math.random() * 1000) +
                (TextUtils.isEmpty(suffix) ? ".jpg" : suffix);
    }

    private void doUploadPictures(int position) {
        String phone = mApplication.getUser().getPhone();
        String localPath = images.get(position).getLocalPath();
        mContext.addDisposableIoMain(ossController.uploadPicturesSync(phone, localPath, false), (String s) -> {
            images.get(position).setOssUrl(s);
            if (images.size() - 1 <= position) {
                mSuccessListener.handler(s);
            } else {
                doUploadPictures(position + 1);
            }
        }, (Throwable throwable) -> {
            mFailListener.handler(throwable.getMessage());
        });
    }


    /**
     * 插入本地地址
     *
     * @param key
     * @param imgPath
     */
    public void putImagePath(int key, String imgPath) {
        for (int i = 0; i < images.size(); i++) {
            UploadImage uploadImage = images.get(i);
            if (uploadImage.getId() == key) {
                uploadImage.setLocalPath(imgPath);
                return;
            }
        }
        UploadImage uploadImage = new UploadImage(key, imgPath);
        images.add(uploadImage);
    }

    public UploadImage remove(int key) {
        UploadImage remove = images.remove(key);
        return remove;
    }

    public String getLocalPath(int key) {
        for (int i = 0; i < images.size(); i++) {
            UploadImage uploadImage = images.get(i);
            if (uploadImage.getId() == key) {
                return uploadImage.getLocalPath();
            }
        }
        return null;
    }

    public String getOssUrl(int key) {
        for (int i = 0; i < images.size(); i++) {
            UploadImage uploadImage = images.get(i);
            if (uploadImage.getId() == key) {
                return uploadImage.getOssUrl();
            }
        }
        return null;
    }

    class UploadImage {
        private int key;
        private String localPath;
        private String ossUrl;

        public UploadImage(int key, String localPath) {
            this.key = key;
            this.localPath = localPath;
        }

        public int getId() {
            return key;
        }

        public void setId(int id) {
            this.key = id;
        }

        public String getLocalPath() {
            return localPath;
        }

        public void setLocalPath(String localPath) {
            this.localPath = localPath;
        }

        public String getOssUrl() {
            return ossUrl;
        }

        public void setOssUrl(String ossUrl) {
            this.ossUrl = ossUrl;
        }
    }
}

